﻿Public Class xtf_LISTADOdeudasTercero_
    Public dts_informe As New dts_informe_1
    Public PERMISOImprimir As String = ""


#Region "Total registros ..."

    Private Sub gdv_general_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        bsi_registros.Caption = "Total Registros: " & gdv_general.RowCount
    End Sub

#End Region

#Region "General"
    Private Sub bbi_cerrar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_cerrar.ItemClick
        Me.Close()
    End Sub

    Private Sub btn_Cerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Cerrar.Click
        Me.Close()
    End Sub

    Private Sub bbi_actualizar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_actualizar.ItemClick
        IniciarLista()
    End Sub

    Private Sub xtf_Listado_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        guardar_config_usuariocolumna_()
    End Sub

    Private Sub guardar_config_usuariocolumna_()
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(UsuarioLOG.idusuario, Me.Name) Then
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.Modificar()
        Else
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.idusuario = UsuarioLOG.idusuario
            obj_config_usuariocolumna_.modulo = Me.Name
            obj_config_usuariocolumna_.Nuevo()
        End If
    End Sub

    Public Sub FiltrarColumnas()
        Dim int_IDUsuario As Integer = UsuarioLOG.idusuario
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        gdv_general.BeginUpdate()
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(int_IDUsuario, Me.Name) Then
            SetLayoutData(gdv_general, obj_config_usuariocolumna_.xml)
        End If

        PerzonalizarControl(gdc_general)

        gdv_general.EndUpdate()
    End Sub

    Private Function GetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView) As Byte()
        Dim stream As New System.IO.MemoryStream()
        prm_GridView.SaveLayoutToStream(stream)
        Return stream.GetBuffer()
    End Function

    Private Sub SetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView, ByVal data As Byte())
        If data Is Nothing OrElse data.Length = 0 Then
            Return
        End If
        Dim stream As New System.IO.MemoryStream(data)
        Try
            prm_GridView.RestoreLayoutFromStream(stream)
        Catch ex As Exception
            Throw New Exception("Wrong data format", ex)
        End Try
    End Sub

    Private Sub bbi_columnas_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_columnas.ItemClick
        gdv_general.ColumnsCustomization()
    End Sub
#End Region

    Public Sub New()

        Me.Cursor = Cursors.WaitCursor
        InitializeComponent()
        PERMISOImprimir = "015001002"
        lbl_modulo.Text = "Deudas Clientes / Proveedores"
        Me.Text = lbl_modulo.Text
        lbl_modulodescripcion.Text = "(detallado por días de la semana)"
        dtp_fechaDesde.DateTime = Now.Date

        IniciarLista()
        Me.Cursor = Cursors.Default



        Dim desde As DateTime = Now
        Dim hasta As DateTime = Now
        dtp_fechaDesde.DateTime = desde
        cbo_tipo.SelectedIndex = 0

    End Sub

    Private Sub cargarTercero_()
        Dim col_ As New Collections.Generic.List(Of CustomListItem2)

        Dim elemento As New CustomListItem2
        elemento.text = "TODOS"
        elemento.var_pkey = 0
        col_.Add(elemento)

        If cbo_tipo.SelectedIndex = 0 Then
            Dim cliente_ As New cls_cliente_
            If cliente_.CargarTodos(True) Then
                For Each cliente As cls_cliente_ In cliente_.Items
                    Dim item As New CustomListItem2
                    item.objeto = cliente
                    item.text = cliente.ToString
                    item.var_pkey = cliente.tercero.idtercero
                    col_.Add(item)
                Next
            End If
        Else
            Dim proveedor_ As New cls_proveedor_
            If proveedor_.CargarTodos(True) Then
                For Each proveedor As cls_proveedor_ In proveedor_.Items
                    Dim item As New CustomListItem2
                    item.objeto = proveedor
                    item.text = proveedor.ToString
                    item.var_pkey = proveedor.tercero.idtercero
                    col_.Add(item)
                Next
            End If
        End If

        cargarCombo(cbo_tercero, col_)

    End Sub

    Public Sub IniciarLista()
        Try
            gdc_general.BeginUpdate()

            gdc_general.DataSource = dts_informe.Tables("asiento__reporte")
        
            gdv_general.PopulateColumns()

            gdv_general.Columns("razonsocial").Caption = "Razón Social"
            gdv_general.Columns("nombrefantasia").Caption = "Nombre de Fantasía"

            gdc_general.EndUpdate()
            FiltrarColumnas()
          
            btn_buscar_Click(Nothing, Nothing)
        Catch ex As Exception
            'Dim frmError As New frm_ErrorManager(ex.Message)
        End Try
    End Sub
    

    Public Sub btn_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar.Click
        Dim dte_lunes As Date = dtp_fechaDesde.DateTime
        Dim dte_sel As Date = dtp_fechaDesde.DateTime

        dts_informe.Tables("asiento__reporte").Clear()

        While Not Format(dte_lunes, "dddd") = "lunes"
            dte_lunes = DateAdd(DateInterval.Day, -1, dte_lunes)
        End While

        Dim obj_command As New SqlClient.SqlCommand()
        Dim obj_Conexion As New cls_Conexion
        obj_Conexion.Conectar()
        If cbo_tercero.EditValue = 0 Then
            If cbo_tipo.SelectedIndex = 0 Then
                With obj_command
                    .CommandType = CommandType.StoredProcedure
                    .Connection = obj_Conexion.obj_SqlConnection
                    .CommandText = "asiento__reporteCliente_"
                    .Parameters.Add("@lunes", SqlDbType.DateTime).Value = dte_lunes
                End With
            Else
                With obj_command
                    .CommandType = CommandType.StoredProcedure
                    .Connection = obj_Conexion.obj_SqlConnection
                    .CommandText = "asiento__reporteProveedor_"
                    .Parameters.Add("@lunes", SqlDbType.DateTime).Value = dte_lunes
                End With
            End If
        Else
            With obj_command
                .CommandType = CommandType.StoredProcedure
                .Connection = obj_Conexion.obj_SqlConnection
                .CommandText = "asiento__reporteXidtercero"
                .Parameters.Add("@lunes", SqlDbType.DateTime).Value = dte_lunes
                .Parameters.Add("@idtercero", SqlDbType.Int).Value = cbo_tercero.EditValue
            End With
        End If
        

        Dim obj_Adapter As New SqlClient.SqlDataAdapter(obj_command)
        gdv_general.BeginDataUpdate()
        obj_Adapter.Fill(dts_informe.Tables("asiento__reporte"))
        gdv_general.EndDataUpdate()


        gdv_general.Columns("lunes").Caption = "Lunes " & Format(DateAdd(DateInterval.Day, 0, dte_lunes.Date), "dd/MM/yy") & ""
        gdv_general.Columns("martes").Caption = "Martes " & Format(DateAdd(DateInterval.Day, 1, dte_lunes.Date), "dd/MM/yy") & ""
        gdv_general.Columns("miercoles").Caption = "Miercoles " & Format(DateAdd(DateInterval.Day, 2, dte_lunes.Date), "dd/MM/yy") & ""
        gdv_general.Columns("jueves").Caption = "Jueves " & Format(DateAdd(DateInterval.Day, 3, dte_lunes.Date), "dd/MM/yy") & ""
        gdv_general.Columns("viernes").Caption = "Viernes " & Format(DateAdd(DateInterval.Day, 4, dte_lunes.Date), "dd/MM/yy") & ""
        gdv_general.Columns("sabado").Caption = "Sabado " & Format(DateAdd(DateInterval.Day, 5, dte_lunes.Date), "dd/MM/yy") & ""
        gdv_general.Columns("domingo").Caption = "Domingo " & Format(DateAdd(DateInterval.Day, 6, dte_lunes.Date), "dd/MM/yy") & ""

        For Each col As DevExpress.XtraGrid.Columns.GridColumn In gdv_general.Columns
            If col.Caption.Contains(Format(dte_sel.Date, "dd/MM/yy")) Then
                col.AppearanceHeader.Font = New Font(col.AppearanceHeader.Font, FontStyle.Bold)
                col.AppearanceCell.Font = New Font(col.AppearanceHeader.Font, FontStyle.Bold)
            Else
                col.AppearanceHeader.Font = New Font(col.AppearanceHeader.Font, FontStyle.Regular)
                col.AppearanceCell.Font = New Font(col.AppearanceHeader.Font, FontStyle.Regular)
            End If
        Next
        'Dim report As New xtr_REPORTElistaprecio2
        'report.DataSource = dts_Movimientos

        obj_Conexion.Desconectar()

        'Return report
    End Sub

    Public Sub bbi_imprimir_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_imprimir.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEdeudasTercero_ = generarReporte()
            Try
                report.Print()
            Catch ex As Exception
                ErrManagerShow("Error inesperado.", ex.Message, xtf_ErrManagerAlerta.errManagerImg.img_Error, xtf_ErrManagerAlerta.errManagerBtn.btn_SalirDelSistema)
            End Try
        End If
    End Sub

    Public Sub bbi_exportarPDF_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarPDF.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEdeudasTercero_ = generarReporte()

            Dim SAVEFILE As New SaveFileDialog
            SAVEFILE.Filter = "PDF (*.PDF)|*.PDF"
            SAVEFILE.FilterIndex = 2
            If SAVEFILE.ShowDialog() = DialogResult.OK Then
                report.ExportToPdf(SAVEFILE.FileName)
            End If
        End If
    End Sub

    Public Sub bbi_vistaprevia_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_vistaprevia.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEdeudasTercero_ = generarReporte()
            report.ShowPreview()
        End If
    End Sub

    Public Sub bbi_exportarExcel_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarExcel.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEdeudasTercero_ = generarReporte()
            Dim SAVEFILE As New SaveFileDialog
            SAVEFILE.Filter = "XLS (*.XLS)|*.XLS"
            SAVEFILE.FilterIndex = 2
            If SAVEFILE.ShowDialog() = DialogResult.OK Then
                report.ExportToXls(SAVEFILE.FileName)
            End If
        End If
    End Sub

    Private Sub btn_exportarImprimir_Click(sender As System.Object, e As System.EventArgs) Handles btn_exportarImprimir.Click
        bbi_vistaprevia_ItemClick(Nothing, Nothing)
    End Sub

    Private Function generarReporte() As xtr_REPORTEdeudasTercero_
        Dim report As New xtr_REPORTEdeudasTercero_
        report.DataSource = dts_informe

        report.lbl_lunes.Text = gdv_general.Columns("lunes").Caption
        report.lbl_martes.Text = gdv_general.Columns("martes").Caption
        report.lbl_miercoles.Text = gdv_general.Columns("miercoles").Caption
        report.lbl_jueves.Text = gdv_general.Columns("jueves").Caption
        report.lbl_viernes.Text = gdv_general.Columns("viernes").Caption
        report.lbl_sabado.Text = gdv_general.Columns("sabado").Caption
        report.lbl_domingo.Text = gdv_general.Columns("domingo").Caption

        report.lbl_titulo.Text = "Cliente: " & cbo_tercero.Text
        report.lbl_subtitulo.Text = "Deudas: desde el " & dtp_fechaDesde.DateTime.ToShortDateString & " hasta el " & DateAdd(DateInterval.Day, 6, dtp_fechaDesde.DateTime).ToShortDateString

        Return report
    End Function

    Private Sub cbo_tipo_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cbo_tipo.SelectedIndexChanged
        cargarTercero_()
    End Sub
End Class